#include <reg52.h>
typedef unsigned char uint8;
typedef unsigned int uint16;

#define FOSC 11059200UL
#define BAUD 9600UL

#define WAIT_TIME() do{while(!TF0);TF0=0;}while(0)
sbit TXD2=P3^1;
sbit RXD2=P3^0;

//初始化计时器0
void init_timer0()
{
	TMOD&=0XF0;
	TMOD|=0X02;
	TH0=256-FOSC/(12*BAUD);
	TL0=TH0;
	TF0=0;
	TR0=0;
}

//发送一字节数据
void UART_send_byte(uint8 dat)
{
	uint8 len=8;
	TL0=TH0;
	TR0=1;
	TXD2=0;
	WAIT_TIME();
	while(len--)
	{
		TXD2=(bit)(dat&0x01);
		WAIT_TIME();
		dat=dat>>1;
	}
	TXD2=1;
	WAIT_TIME();
	TR0=0;
}

//接收一字节数据
uint8 UART_read_byte()
{
	uint8 len=8,dat=0;
	while(RXD2);
	TR0=1;
	TL0=256-FOSC/(12*BAUD)/2;
	WAIT_TIME();
	WAIT_TIME();
	while(len--)
	{
		dat>>=1;
		if(RXD2)
		{
			dat|=0x80;
		}
		WAIT_TIME();
	}
	WAIT_TIME();
	TR0=0;
	return dat;
}

//main函数
void main()
{
	uint8 a;
	init_timer0();
	while(1)
	{
		UART_send_byte('i');
		UART_send_byte('p');
		UART_send_byte('u');
		UART_send_byte('t');
		UART_send_byte(':');
		a=UART_read_byte();
		UART_send_byte(a);
		UART_send_byte('\r');
		UART_send_byte('\n');
	}
}

